<script setup lang="ts">
import { ref, markRaw } from "vue";
import { useColumns } from "./compower_columns";
import { useEditColumns } from "./edit_compower_columns";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Empty from "@/assets/common/empty.svg?component";
import Plus from "~icons/ep/plus";
import AddFill from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import "plus-pro-components/es/components/dialog-form/style/css";
import { getProductInfo, setProductInfo, addProductInfo } from "@/api/finance";
import {
  underscoreToCamel,
  numberNotNull,
  stringNotNull
} from "@/utils/common";
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import { ElMessageBox, ElMessage, type Action } from "element-plus";
const props = defineProps({
  type: {
    type: Number,
    default: 4
  },
  add: {
    type: Boolean,
    default: false
  },
  edit: {
    type: Boolean,
    default: false
  },
  delete: {
    type: Boolean,
    default: false
  }
});

const rules = {
  title: [
    {
      required: true,
      message: "商品标题必填"
    }
  ],
  skus: [
    {
      required: true,
      message: "sku必填"
    }
  ]
};

const formColumns: PlusColumn[] = [
  {
    label: "商品标题",
    width: 120,
    prop: "title",
    valueType: "input",
    tooltip: "名称最多显示6个字符"
  },
  {
    label: "支付类型",
    prop: "payType",
    valueType: "checkbox",
    options: [
      {
        label: "余额",
        value: 0
      },
      {
        label: "收益",
        value: 1
      },
      {
        label: "积分",
        value: 2
      },
      {
        label: "消费券",
        value: 3
      }
    ]
  },
  {
    label: "Sku列表",
    prop: "skus"
  },
  {
    label: "是否发布",
    prop: "status",
    valueType: "radio",
    options: [
      {
        label: "下架",
        value: "0"
      },
      {
        label: "上架",
        value: "1"
      }
    ]
  }
];
const visible = ref(false);
const confirmLoading = ref(false);
const edit = ref(false);
const values = ref<FieldValues>({});

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  loadData,
  onSizeChange,
  onCurrentChange
} = useColumns(props.type);
if (!props.delete && !props.edit) {
  columns.pop();
}
const { editColumns } = useEditColumns();
function deleteClick(row) {
  ElMessageBox.confirm("是否删除", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    type: "error",
    icon: markRaw(Delete),
    callback: async (action: Action) => {
      // 在这里执行删除操作
      if (action === "confirm") {
        console.log("执行删除操作");
        try {
          const params = {
            fgId: row.fgId,
            isDelete: 1
          };
          const res = await setProductInfo(params);
          loadData();
          ElMessage.success("删除成功");
        } catch (error) {
          console.log(error, "error");
        }
      }
    }
  });
}
const onAdd = () => {
  if (!values.value.skus) {
    values.value.skus = [];
  }
  values.value.skus.push({
    sub_title: "",
    money: "",
    cycle: 0,
    income: ""
  });
};
const onDel = row => {
  const index = values.value.skus.indexOf(row);
  if (index !== -1) values.value.skus.splice(index, 1);
};

const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  updatedValues.skus = underscoreToCamel(updatedValues.skus);
  // delete updatedValues.skus;
  updatedValues.contractUrl = stringNotNull(updatedValues.contractUrl);
  updatedValues.docTemplateId = stringNotNull(updatedValues.docTemplateId);
  console.log("updatedValues", updatedValues);
  confirmLoading.value = true;
  if (edit.value) {
    try {
      await setProductInfo(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      updatedValues.type = props.type;
      updatedValues.maxsale = 0;
      updatedValues.iconimage = "";
      updatedValues.images = "";
      updatedValues.money = "0";
      updatedValues.pv = "0";
      updatedValues.sjsj = 1;
      updatedValues.sf = "0";
      updatedValues.hbz = "0";
      updatedValues.sjType = 1;
      updatedValues.num = 0;
      updatedValues.tai = 0;
      updatedValues.minsale = 1;
      updatedValues.xg = 0;
      updatedValues.content = "";

      console.log("add", updatedValues);
      await addProductInfo(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};
const editClick = async row => {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  try {
    const res = await getProductInfo(row.fgId);

    res.data.payType = JSON.parse(res.data.payType);
    Object.assign(values.value, res.data);
    // values.value = { ...res.data };
    console.log(
      "%cres===>>>",
      "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
      "返回的",
      res,
      values.value
    );
    edit.value = true;
    visible.value = true;
  } catch (error) {
    console.log(error, "error");
  }
};
const addProduct = () => {
  console.log("%c点击了添加商品>>>: ", "color: MidnightBlue; font-size: 20px;");
  edit.value = false;
  values.value = {};
  visible.value = true;
};
const formRef = ref();
const tableRef = ref();
const editTableRef = ref();
</script>

<template>
  <div class="flex flex-col">
    <div v-if="props.add" class="flex flex-row items-end justify-end mb-4">
      <el-button type="primary" @click="addProduct">
        <el-icon :size="15" color="#fff">
          <IconifyIconOffline :icon="Plus" />
        </el-icon>
        添加商品
      </el-button>
    </div>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #sku="{ row }">
        <div class="flex flex-row flex-wrap gap-2">
          <div
            v-for="item in row.skus"
            :key="item.id"
            class="w-[auto] flex flex-col"
          >
            <el-tag type="primary" class="color-[#333] text-size-[20px]">{{
              item.sub_title
            }}</el-tag>
          </div>
        </div>
      </template>
      <template #status="{ row }">
        <el-tag v-if="row.status == '1'" type="success">上架</el-tag>
        <el-tag v-else type="danger">下架</el-tag>
      </template>
      <template #operation="{ row }">
        <el-button
          v-if="props.edit"
          type="primary"
          size="small"
          @click="editClick(row)"
          >编辑</el-button
        >
        <el-button
          v-if="props.delete"
          type="danger"
          size="small"
          @click="deleteClick(row)"
        >
          删除
        </el-button>
      </template>
    </pure-table>
    <PlusDialogForm
      v-if="(values && values.skus && edit) || !edit"
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      :title="edit ? '编辑商品' : '添加商品'"
      width="80%"
      @confirm="handleSubmit"
    >
      <template #status="{ row }">
        <el-tag v-if="row.status == '1'" type="success">上架</el-tag>
        <el-tag v-else type="danger">下架</el-tag>
      </template>
      <template #plus-field-skus>
        <pure-table
          ref="editTableRef"
          border
          row-key="id"
          align-whole="center"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :data="values.skus"
          :columns="editColumns"
        >
          <template #empty>
            <Empty fill="var(--el-svg-monochrome-grey)" class="m-auto" />
          </template>
          <template #append>
            <el-button
              type="success"
              class="w-full my-2!"
              :icon="useRenderIcon(AddFill)"
              @click="onAdd"
            >
              添加一行数据
            </el-button>
          </template>
          <template #operation="{ row }">
            <div
              v-if="row.id && row.id > 0"
              class="flex flex-row gap-2 items-center"
            >
              是否删除<el-switch
                v-model="row.isDelete"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
            <el-button
              v-else
              class="reset-margin"
              link
              type="primary"
              :icon="useRenderIcon(Delete)"
              @click="onDel(row)"
            />
          </template>
        </pure-table>
      </template>
    </PlusDialogForm>
  </div>
</template>

<style scoped></style>
